package ro.savatech.pg.cmd;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

import ro.savatech.pg.flightlog.Device;

/**
 * Main command line interpreter.
 * 
 * @author Dan Corneanu
 * 
 */
public class MainCLI {

	public static void main(String[] args) {
		Options options = new Options();

		Option cmdOption = new Option("c", "command", true, String.format(
				"Command to execute: %s", Cmd.dumpMem.name()));
		options.addOption(cmdOption);

		Option dumpfileOption = new Option("f", "file", true,
				"File to dump memory to.");
		options.addOption(dumpfileOption);

		Option portOption = new Option("p", "port", true,
				"Serial port name to connect through to the device.");
		options.addOption(portOption);

		CommandLineParser parser = new PosixParser();
		try {
			CommandLine cmd = parser.parse(options, args);
			if (!cmd.hasOption(cmdOption.getOpt())) {
				printHelpAndExit(args, options);
			}

			if (!cmd.hasOption(dumpfileOption.getOpt())) {
				printHelpAndExit(args, options);
			}

			if (!cmd.hasOption(portOption.getOpt())) {
				printHelpAndExit(args, options);
			}

			String portValue = cmd.getOptionValue(portOption.getOpt());

			String dumpfileValue = cmd.getOptionValue(dumpfileOption.getOpt());
			File dumpFile = new File(dumpfileValue);

			String cmdValue = cmd.getOptionValue(cmdOption.getOpt());
			try {
				if (Cmd.dumpMem.name().equals(cmdValue)) {
					dump(portValue, dumpFile);
				}
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(2);
			}

		} catch (ParseException e) {
			System.err.println("Parsing failed.  Reason: " + e.getMessage());
			printHelpAndExit(args, options);
		}
	}

	private static void dump(String portValue, File dumpFile)
			throws IOException {
		dumpFile.createNewFile();
		FileOutputStream os = null;
		Device device = new Device();
		try {
			device.connectOnPort(portValue);
			os = new FileOutputStream(dumpFile);

			device.dumpConfigurationMemory(os);
			device.dumpFlightMemory(os);

			os.flush();
		} finally {
			if (null != os) {
				os.close();
			}
			device.disconnect();
		}
	}

	private static void printHelpAndExit(String[] args, Options options) {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp(MainCLI.class.getName(), options);
		System.exit(2);
	}
}